import React, { useMemo } from 'react';
import TableContext, { createContext } from '../context/table';
import * as utils from '../utils';

import type { AnyObject, DisplayTableProps, TableContextRef } from '../type';

export interface Props<T extends AnyObject> extends DisplayTableProps<T> {
  Table?: <T extends AnyObject, P>(
    props: P,
    ref: React.ForwardedRef<TableContextRef<T>>,
  ) => JSX.Element;
}

function TableContextCom<T extends AnyObject>(
  props: Props<T>,
  ref: React.ForwardedRef<TableContextRef<T>>,
) {
  const { context, Table, ...restProps } = props;
  const TableRef = useMemo(() => utils.getTableRef(Table), [Table]);
  const tableId = useMemo(
    () => props.id || utils.createTableId('table'),
    [props.id],
  );
  const tableContext = useMemo(() => createContext(), [tableId]);
  const tableProps = { ...restProps, id: tableId };
  if (context) {
    return <TableRef {...tableProps} context={context} ref={ref} />;
  } else {
    return (
      <TableContext context={tableContext}>
        <TableRef {...tableProps} context={tableContext} ref={ref} />
      </TableContext>
    );
  }
}

export default utils.getTableRef(TableContextCom);
